//
//  TMNearbyController.m
//  国学商家管理
//
//  Created by Tao Li on 2018/7/4.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "TMNearbyController.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <MAMapKit/MAMapKit.h>
#import "TMNearbyBusinessController.h"
#import "TMNearbyViewModel.h"
#import "TMSearchModel.h"
#import "TMShopHomeController.h"
#import "TMAnnotationCell.h"
#import "TMAnnoSelectView.h"
@interface TMNearbyController ()<AMapLocationManagerDelegate,MAMapViewDelegate,AMapSearchDelegate>
@property (nonatomic, strong)MAMapView *mapView;
@property (nonatomic, strong) AMapLocationManager *locationManager;
@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) NSMutableArray *annotations;
@property (nonatomic, strong) TMNearbyViewModel *viewModel;
@property (nonatomic, assign) CLLocationCoordinate2D coor2d;
@property (nonatomic, strong) NSMutableArray *modelArray;
@end

@implementation TMNearbyController
-(NSMutableArray *)modelArray
{
    if (!_modelArray) {
        _modelArray = [NSMutableArray array];
    }
    return _modelArray;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;
    [self displayLocationManager];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"附近";
    [self initMapview];
    [self displayLocationManager];


}
- (AMapSearchAPI *)search {
    if (_search == nil) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
    }
    return _search;
}
- (void)initMapview{
    _mapView = [[MAMapView alloc]initWithFrame:CGRectMake(0, 64, kWindowW, kWindowH-64)];
    _mapView.delegate = self;
    _mapView.compassOrigin = CGPointMake(_mapView.compassOrigin.x, 22);
    _mapView.scaleOrigin = CGPointMake(_mapView.compassOrigin.x, 22);
    _mapView.zoomLevel = 13.1;
    _mapView.showsCompass = NO;
    [self.view addSubview:_mapView];
    
}
#pragma location delegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation{
    NSLog(@"%@", userLocation);

}
#pragma -mark 大头针相关
- (void)initAnnotations:(NSMutableArray *)arr
{
    if (self.mapView.annotations.count >0) {
        [self.mapView removeAnnotations:self.mapView.annotations];
    }
    self.annotations = [NSMutableArray array];
    for (int i = 0; i < arr.count; ++i)
    {
        TMSearchModel *model = arr[i];
        NSArray *lat = [model.lat_long componentsSeparatedByString:@","];
        MAPointAnnotation *a1 = [[MAPointAnnotation alloc] init];
        a1.coordinate = (CLLocationCoordinate2D){[lat[0] floatValue], [lat[1] floatValue]};
        a1.title      = [NSString stringWithFormat:@"%@", model.username];
        [self.annotations addObject:a1];
    }
    [self.mapView addAnnotations:self.annotations];
//    [self.mapView showAnnotations:self.annotations edgePadding:UIEdgeInsetsMake(20, 20, 20, 80) animated:YES];
    [self.mapView showAnnotations:self.annotations animated:YES];
}
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
//    if ([annotation isKindOfClass:[MAPointAnnotation class]])
//    {
//        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
//        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
//        //annotationView.image = [UIImage imageNamed:@"地标"];
//        if (annotationView == nil)
//        {
//            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
//        }
//        annotationView.canShowCallout               = YES;
//        annotationView.animatesDrop                 = YES;
//        annotationView.draggable                    = YES;
//        annotationView.image = [UIImage imageNamed:@"地标"];
//        annotationView.rightCalloutAccessoryView    = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
//        annotationView.pinColor                     = MAPinAnnotationColorRed;
//
//        return annotationView;
//    }
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *customReuseIndetifier = @"customReuseIndetifier";

        TMAnnotationCell *annotationView = (TMAnnotationCell*)[mapView dequeueReusableAnnotationViewWithIdentifier:customReuseIndetifier];

//        if (annotationView == nil)
//        {
            annotationView = [[TMAnnotationCell alloc] initWithAnnotation:annotation reuseIdentifier:customReuseIndetifier];
            annotationView.canShowCallout = NO;
            annotationView.calloutView.nameLabel.text = annotation.title;
            annotationView.draggable = YES;
            annotationView.calloutOffset = CGPointMake(0, -5);
       // }
        __weak typeof(annotationView) weakself = annotationView;
        annotationView.block = ^(NSInteger tags) {
            if ([weakself.annotation.title isEqualToString:@"当前位置"]) {
                return;
            }
            TMShopHomeController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMShopHomeController"];
            for (TMSearchModel *model in self.modelArray) {
                if ([weakself.annotation.title isEqualToString:model.username]) {
                    vc.shopid = model.sid;
                }
            }
            [self.navigationController pushViewController:vc animated:YES];
        };
        return annotationView;
    }
  return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view{
//    TMNearbyBusinessController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMNearbyBusinessController"];
//    for (TMSearchModel *model in self.modelArray) {
//        if ([view.annotation.title isEqualToString:model.username]) {
//            vc.cid = model.sid;
//        }
//    }
//    [self.navigationController pushViewController:vc animated:YES];
    if ([view.annotation.title isEqualToString:@"当前位置"]) {
        return;
    }
    TMShopHomeController *vc = [[UIStoryboard storyboardWithName:@"Nearby" bundle:nil] instantiateViewControllerWithIdentifier:@"TMShopHomeController"];
        for (TMSearchModel *model in self.modelArray) {
            if ([view.annotation.title isEqualToString:model.username]) {
                vc.shopid = model.sid;
            }
        }
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma-mark 定位
- (void)displayLocationManager{
    self.locationManager = [[AMapLocationManager alloc] init];
    //设置精度
    [self.locationManager setDesiredAccuracy:kCLLocationAccuracyHundredMeters];
    //设置定位超时时间
    self.locationManager.locationTimeout = 10;
    //设置反地理编码超时时间
    self.locationManager.reGeocodeTimeout = 10;
    //请求定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        if (error) {
            NSLog(@"%@", error.localizedDescription);
        }
        //打印定位到的位置坐标  location:(40.037471,116.370002)
        NSLog(@"location:(%f,%f)", location.coordinate.latitude,location.coordinate.longitude);
        self.coor2d = location.coordinate;
        if (regeocode) {
            //反地理编码,打印定位到的地址信息  reGeocode:北京市海淀区东升镇庄盛百货(清河店)
            NSLog(@"reGeocode:%@", regeocode.formattedAddress);
            [self getDataWith:self.coor2d];
        }

    }];
}
- (void)getDataWith:(CLLocationCoordinate2D)coor{
    NSArray *arr = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%f", coor.latitude],[NSString stringWithFormat:@"%f", coor.longitude], nil];
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *jsonTemp = [jsonString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *jsonResult = [jsonTemp stringByReplacingOccurrencesOfString:@" " withString:@""];
    self.viewModel = [[TMNearbyViewModel alloc]init];
    [self.viewModel getNearbyCourseWithParam:jsonResult Success:^(id responseObject) {
        self.modelArray = responseObject;
        [self initAnnotations: responseObject];
    } Failed:^(NSString *error) {
        
    }];
}

- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode
{
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    if (reGeocode)
    {
        NSLog(@"reGeocode:%@", reGeocode);
    }
}
@end
